package cn.easy.rest.controller;

import cn.easy.api.UserService;
import cn.easy.common.pojo.EasyResult;
import cn.easy.common.util.TokenUtil;
import cn.easy.pojo.User;
import cn.easy.rest.dao.JedisClient;
import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/user")
@Controller
public class UserController {
    @Reference
    private UserService userService;
    @Autowired
    private JedisClient jedisClient;


    /**
     * 新增一个用户
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public EasyResult insertUser(@RequestBody User user) {
        System.out.println("hello  this is me ");
        //检查必要的参数
        if (user.getUserLoginName() == null ||
                user.getUserNickName() == null ||
                user.getUserPassword() == null ||
                user.getUserEmail() == null) {
//            return EasyResult.build(500, "必要的项缺失");
            return EasyResult.build(500, "some");
        }
        try {
            userService.insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }
        return EasyResult.ok();
    }


    /**
     * 根据用户的昵称查询用户
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchUserByNickName/{nickname}", method = RequestMethod.GET)
    public EasyResult searchUserByNickName(@PathVariable(value = "nickname") String nickname) {
        List<User> userList = null;
        //nickname = PathVariableUtil.getChinese(nickname);
        try {
            userList = userService.searchUserByNickName(nickname);
            return EasyResult.build(200, "success", userList);
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 根据用户的账号 查询用户
     *
     * @param loginname
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchUserByLoginName/{loginname}", method = RequestMethod.GET)
    public EasyResult searchUserByLoginName(@PathVariable(value = "loginname") String loginname) {
        User user = null;
        try {
            user = userService.searchUserByLoginName(loginname);
            return EasyResult.build(200, "success", user);
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 更新用户信息  需要做身份验证
     * 不能更新用户的状态，以及key还有用户的账号名
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public EasyResult updateUser(@RequestBody User user) {
        /*--------------判断必要的参数是不是已经有了------------*/

        //判断用户的key是不是为空
        if (user.getUserKey() == null) return EasyResult.fail("请提供用户的key");
        //判断要更新的用户的主键
        if (user.getUserId() == null) return EasyResult.fail("请提供用户的主键");

        try {
            userService.updateUser(user);
            return EasyResult.ok();
        } catch (Exception e) {

            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 更新用户的key
     *
     * @param key
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUserKey/{key}", method = RequestMethod.GET)
    public EasyResult updateUserKey(@PathVariable(value = "key") String key) {
        try {
            String newKey = userService.updateUserKey(key);
            return EasyResult.ok(newKey);
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 拿到用户的key
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUserKey", method = RequestMethod.POST)
    public EasyResult getUserKey(@RequestBody Map map) {
        String name;
        String password;
        if (map.containsKey("name")) name = map.get("name").toString();
        else return EasyResult.fail("请提供账号");
        if (map.containsKey("password")) password = map.get("password").toString();
        else return EasyResult.fail("请提供密码");
        try {
            String userKey = userService.getUserKey(name, password);
            return EasyResult.ok(userKey);
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    @RequestMapping(value = "/ceshi")
    @ResponseBody
    public EasyResult ceshi() {
        userService.Ceshi();
        return EasyResult.ok();
    }

    /**
     * 用户登录的接口，将用户返回一个token ,这个token可以拿到用户的基本信息
     *
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public EasyResult login(@RequestBody Map map) {
        String userLoginName;//登录用户名
        String userPassword; //登录密码
        ObjectMapper objectMapper = new ObjectMapper();
        String token;//用户token
        //数据检查
        if (map.containsKey("userLoginName")) {
            userLoginName = map.get("userLoginName").toString();
        }
        else {
            return EasyResult.fail("缺少登录用户名");
        }
        if (map.containsKey("userPassword")) userPassword = map.get("userPassword").toString();
        else return EasyResult.fail("缺少用户密码");
        //登录
        User user = userService.login(userLoginName, userPassword);

        if (user == null) return EasyResult.fail("账号或者密码错误");
        else {
            if(user.getUserState()!=1) return EasyResult.fail("当前该用户不允许登录！");
            //将登录信息放入redis数据库中
            try {
                token = TokenUtil.getToken(user.getUserLoginName());
                jedisClient.set(token, objectMapper.writeValueAsString(user));
                jedisClient.expire(token, 15 * 60);//15分钟不操作自动退出
            } catch (Exception e) {
                e.printStackTrace();
                return EasyResult.fail("用户登录异常");
            }
            return EasyResult.ok(token);
        }
    }

    /**
     * 用户退出系统
     *
     * @param token
     * @return
     */
    @RequestMapping("/exit/{token}")
    @ResponseBody
    public EasyResult exit(@PathVariable String token) {
        //检查token是否存在数据库中，或者说token有没有过期
        String s = jedisClient.get(token);
        if (s != null && !StringUtils.isEmpty(s)) {
            jedisClient.del(token);
            return EasyResult.ok();
        } else {
            return EasyResult.fail("没有登录，或者登录已经过期");
        }
    }


}
